package com.ihrm.system.service;

import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.common.utils.PermissionConstants;
import com.ihrm.domain.system.Permission;
import com.ihrm.domain.system.Role;
import com.ihrm.system.mapper.PermissionDao;
import com.ihrm.system.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class RoleService {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private IdWorker idWorker;

	/**
	 * 添加角色
	 */
	public Result save(Role role) {
		role.setId(idWorker.nextId()+"");
		roleMapper.save(role);
		return Result.SUCCESS();
	}

	/**
	 * 分页查询所有角色
	 */
	public Page<Role> findAll(String companyId, int page, int size) {
		Specification<Role> specification = new Specification<Role>() {
			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				return cb.equal(root.get("companyId").as(String.class), companyId);
			}
		};
		return roleMapper.findAll(specification, PageRequest.of(page - 1, size));
	}

	/**
	 * 根据id查询角色
	 */
	public Role findById(String id) {
		return roleMapper.findById(id).get();
	}

	/**
	 * 更新角色
	 */
	public Result update(Role role) {
		Role roleDb = roleMapper.getOne(role.getId());
		roleDb.setName(role.getName());
		roleDb.setDescription(role.getDescription());
		roleMapper.save(roleDb);
		return new Result(ResultCode.SUCCESS);
	}

	/**
	 * 删除角色
	 */
	public Result delete(String id) {
		roleMapper.deleteById(id);
		return new Result(ResultCode.SUCCESS);
	}

	/**
	 * 为角色分配权限
	 * @param roleId
	 * @param perIds
	 */
	@Autowired
	private PermissionDao permissionDao;
	public void assignPers(String roleId, List<String> permIds) {
		//1.根据id查询角色
		Role roleDb = roleMapper.findById(roleId).get();

		//2.设置角色的权限集合
		Set<Permission> perms = new HashSet<>();
		for (String perId : permIds) {
			Permission permission = permissionDao.findById(perId).get();
			//根据父id和类型查询权限api权限列表
			List<Permission> apiList = permissionDao.findByPidAndType(permission.getId(),PermissionConstants.PY_API);
			perms.addAll(apiList);//赋予api权限
			perms.add(permission);//当前菜单或按钮权限
		}
		//3.设置角色和权限集合之间的关系
		roleDb.setPermissions(perms);
		//4.更新权限集合
		roleMapper.save(roleDb);
	}
	
	
}
